import { useEffect, useState, useImperativeHandle, forwardRef, useRef } from 'react';
import { Button, message, Tabs } from 'antd';
import { getMessage, TextWidget } from '@inbiz/react';
import BizHeader from '@inbiz/basic/BizHeader';
import BizBody from '@inbiz/basic/BizBody';
import { getPreView, getEditor } from '@inbiz/utils';
import EasyTypeItem from './EasyTypeItem';
const { TabPane } = Tabs;

const EasyType = forwardRef((props: any, ref) => {
  const {
    dataLoadMode = 'more',
    loadMoreLocation = 'topRight',
    loadMoreText = '查看更多',
    associatePage,
    dynamicdata,
    showTabTitle,
    easyDefaultPage = '1',
    title,
    customClickItem,
  } = props;
  
  // 判断是否为设计页
  const isEditor = getEditor();

  const [activeTab, setActiveTab] = useState<any>(
    localStorage.getItem(props.controlId + 'processTabs') || easyDefaultPage,
  );

  const easyItemRef = useRef({ getGroupData: Function, getProcessData: Function });

  const onLoadMore = () => {
    if (associatePage) {
      let path = associatePage.split(',')[0];
      window.open(getPreView(path) + `?tabKey=${activeTab}`);
    } else {
      // 请联系管理员配置关联页面
      message.warning(getMessage('processCenter.associatedPageIsNotConfigured'));
    }
  };

  const headerProps = {
    ...props,
    extra: dataLoadMode == 'more' && loadMoreLocation == 'topRight' && (
      <Button
        type="link"
        onClick={onLoadMore}
        style={{ padding: 0, fontSize: 'var(--inbiz-font-size-base)' }}
      >
        <TextWidget>{loadMoreText}</TextWidget>
        {' >'}
      </Button>
    ),
  };

  useImperativeHandle(ref, () => ({
    getGroupData: easyItemRef?.current?.getGroupData,
    getProcessData: easyItemRef?.current?.getProcessData,
  }));

  useEffect(() => {
    if (isEditor) {
      setActiveTab(easyDefaultPage);
    } else {
      setActiveTab(localStorage.getItem(props.controlId + 'processTabs') || easyDefaultPage);
    }
  }, [easyDefaultPage]);

  // 本地存储
  useEffect(() => {
    if (activeTab != localStorage.getItem(props.controlId + 'processTabs')) {
      localStorage.setItem(props.controlId + 'processTabs', activeTab);
    }
    // 卸载
    return () => {
      localStorage.removeItem(props.controlId + 'processTabs');
    };
  }, [activeTab]);

  return (
    <>
      <BizHeader {...headerProps} />
      <BizBody {...props}>
        <Tabs
          className={showTabTitle ? 'process-east-tab' : 'process-east-tab process-notabstitle'}
          defaultActiveKey={
            localStorage.getItem(props.controlId + 'processTabs') || easyDefaultPage
          }
          activeKey={activeTab}
          onChange={setActiveTab}
          destroyInactiveTabPane={true}
          tabBarExtraContent={
            loadMoreLocation == 'topRight' &&
            dataLoadMode == 'more' &&
            !title?.status && (
              <Button
                type="link"
                onClick={onLoadMore}
                style={{ padding: 0, fontSize: 'var(--inbiz-font-size-base)' }}
              >
                <TextWidget>{loadMoreText}</TextWidget>
                {' >'}
              </Button>
            )
          }
        >
          {dynamicdata.map((item: { title: string; id: string }) => {
            return (
              <TabPane tab={<TextWidget>{item?.title}</TextWidget>} key={item?.id}>
                <EasyTypeItem
                  processData={item}
                  activeTab={activeTab}
                  {...props}
                  ref={easyItemRef}
                  customClickItem={customClickItem}
                />
              </TabPane>
            );
          })}
        </Tabs>
      </BizBody>
    </>
  );
});

export default EasyType;
